#include "exportrefm.h"
#include <QtXlsx>

using namespace QXlsx;

void calcuCons(const QString &,Format (&)[6]);

exportRefm::exportRefm(QObject *parent) : QObject(parent)
{

}
void exportRefm::setClassMateList(const ClassMate &aFile){
    classMateList.append(aFile);
}

void exportRefm::run(){
    if(!classMateList.isEmpty()){
        create();
        emit end();
    }
    emit idle();
}

int exportRefm::create(){
    QString dir_str = "../Excel";//save path

    Format format;
    format.setHorizontalAlignment(Format::AlignHCenter);
    format.setVerticalAlignment(Format::AlignVCenter);
    format.setBorderStyle(QXlsx::Format::BorderThin);

    Format format1;
    format1.setFontBold(true);
    format1.setHorizontalAlignment(Format::AlignHCenter);
    format1.setVerticalAlignment(Format::AlignVCenter);
    format1.setBorderStyle(QXlsx::Format::BorderThin);

    Format format2;
    format2.setHorizontalAlignment(Format::AlignRight);
    format2.setVerticalAlignment(Format::AlignVCenter);
    format2.setBorderStyle(QXlsx::Format::BorderThin);

    Format formatError;
    formatError.setHorizontalAlignment(Format::AlignRight);
    formatError.setVerticalAlignment(Format::AlignVCenter);
    formatError.setBorderStyle(QXlsx::Format::BorderThin);
    formatError.setFontColor(QColor(Qt::red));

    Format formats[6];
    for (int i=0;i<6;++i) {
        formats[i].setHorizontalAlignment(Format::AlignRight);
        formats[i].setVerticalAlignment(Format::AlignVCenter);
        formats[i].setBorderStyle(QXlsx::Format::BorderThin);
        formats[i].setFontColor(QColor(Qt::black));
    }

    QXlsx::Document xlsx;

    int count=0;
    int colOffset=0;
    int colOffsetC=0;
    int colOffset_sheet2=0;
    QString sheetVAmpName("电压幅值相位");
    QString sheetCAmpName("电流幅值相位");
    QString sheetErrorName("电能误差");
    for (auto beg=classMateList.cbegin();beg!=classMateList.cend();++beg) {
        if(!beg->checked_)continue;
        if(doc.LoadFile(beg->fullPath_.toLocal8Bit())){
            qDebug()<<"file load error";
            doc.PrintError();
            doc.Clear();
            continue;
        }

        int maxOffsetError=0;
        root=doc.RootElement();
        QString deviceNo(root->Attribute("DeviceID"));
        QString testDate(root->Attribute("TestDate"));

        tinyxml2::XMLElement *firstItems = root->FirstChildElement("Items");
        tinyxml2::XMLElement *firstGroupOfItems = firstItems->FirstChildElement("GroupData");
        QString innerValue;
        QString rangev("0");
        QString percentv("100%");
        QString inVoltage("0");
        QString rangec("0");
        QString percentc("100%");
        QString inCurrent("0");
        int offsetType=0;
        int rowOffsetAcmv=0;
        int rowOffsetAcmc=0;
        while(firstGroupOfItems){
            if(0==strcmp("ACMeterVoltage",firstGroupOfItems->Attribute("GroupName"))){
                offsetType=1;
                if(!xlsx.selectSheet(sheetVAmpName))
                {
                    xlsx.addSheet(sheetVAmpName);
                }
                tinyxml2::XMLElement *firstItemsOfGroup = firstGroupOfItems->FirstChildElement("Items");
                tinyxml2::XMLElement *itemData=firstItemsOfGroup->FirstChildElement();

                int col=0+colOffset;
                int row=3;
                while(itemData){
                    if(count==0){
                        int colTmp=0;
                        xlsx.write(row,++colTmp,QString(itemData->Attribute("Index")).toInt()+1,format2);
                        xlsx.mergeCells(CellRange(row,colTmp,row+1,colTmp),format1);
                        xlsx.write(row,++colTmp,"4L",format2);
                        xlsx.mergeCells(CellRange(row,colTmp,row+1,colTmp),format1);
                        xlsx.write(row,++colTmp,"L123",format2);
                        xlsx.mergeCells(CellRange(row,colTmp,row+1,colTmp),format1);

                        auto parmAry=QString(itemData->Attribute("Parameter")).split("_");
                        rangev=parmAry[0].replace("V","").replace("mV","");
                        percentv=parmAry[1].remove('%');
                        inVoltage=QString("%1").arg(rangev.toDouble() * percentv.toDouble() / 100.0);
                        xlsx.write(row,++colTmp,inVoltage,format2);
                        xlsx.mergeCells(CellRange(row,colTmp,row+1,colTmp),format1);

                        rangec=parmAry[2].replace("A","").replace("mA","");
                        percentc=parmAry[3].remove('%');
                        inCurrent=QString("%1").arg(rangec.toDouble() * percentc.toDouble() / 100.0);
                        xlsx.write(row,++colTmp,inCurrent,format2);
                        xlsx.mergeCells(CellRange(row,colTmp,row+1,colTmp),format1);

                        xlsx.write(row+rowOffsetAcmv,++colTmp,"1.0",format2);
                        xlsx.mergeCells(CellRange(row,colTmp,row+1,colTmp),format1);

                        xlsx.write(row,++colTmp,"标准表",format2);
                        xlsx.write(row+1,colTmp,"EUT",format2);
                    }
                    col=7+colOffset;
                    innerValue=itemData->Attribute("ReferenceValue");
                    auto tempAry=innerValue.split(";");
                    for (auto istr:tempAry) {
                        xlsx.write(row,++col,istr,format2);
                    }

                    innerValue=itemData->Attribute("ReferenceValue2");
                    tempAry=innerValue.split(";");
                    for (auto istr:tempAry) {
                        xlsx.write(row,++col,istr,format2);
                    }

                    calcuCons(QString(itemData->Attribute("Conclusion")),formats);

                    col=7+colOffset;
                    innerValue=itemData->Attribute("MeasuredValue");
                    tempAry=innerValue.split(";");
                    int i=0;
                    for (auto istr:tempAry) {
                        xlsx.write(row+1,++col,istr,formats[i]);
                        ++i;
                    }

                    innerValue=itemData->Attribute("MeasuredValue2");
                    tempAry=innerValue.split(";");
                    i=3;
                    for (auto istr:tempAry) {
                        xlsx.write(row+1,++col,istr,formats[i]);
                        ++i;
                    }

                    innerValue=itemData->Attribute("ErrorValue");
                    tempAry=innerValue.split(";");
                    i=0;
                    for (auto istr:tempAry) {
                        xlsx.write(row+1,++col,istr,formats[i]);
                        ++i;
                    }

                    innerValue=itemData->Attribute("ErrorValue2");
                    tempAry=innerValue.split(";");
                    i=3;
                    for (auto istr:tempAry) {
                        xlsx.write(row+1,++col,istr,formats[i]);
                        ++i;
                    }


                    itemData=itemData->NextSiblingElement();
                    row+=2;
                }
                rowOffsetAcmv=row;

            }else if (0==strcmp("ACMeterCurrent",firstGroupOfItems->Attribute("GroupName"))) {
                offsetType=2;
                if(!xlsx.selectSheet(sheetCAmpName))
                {
                    xlsx.addSheet(sheetCAmpName);
                }
                tinyxml2::XMLElement *firstItemsOfGroup = firstGroupOfItems->FirstChildElement("Items");
                tinyxml2::XMLElement *itemData=firstItemsOfGroup->FirstChildElement();

                int col=0+colOffsetC;
                int row=3;
                while(itemData){
                    if(count==0){
                        int colTmp=0;
                        xlsx.write(row,++colTmp,QString(itemData->Attribute("Index")).toInt()+1,format2);
                        xlsx.write(row+1,colTmp,QString(itemData->Attribute("Index")).toInt()+1,format2);
                        xlsx.write(row,++colTmp,"4L",format2);
                        xlsx.write(row+1,colTmp,"4L",format2);
                        xlsx.write(row,++colTmp,"L123",format2);
                        xlsx.write(row+1,colTmp,"L123",format2);

                        auto parmAry=QString(itemData->Attribute("Parameter")).split("_");
                        rangev=parmAry[2].replace("V","").replace("mV","");
                        percentv=parmAry[3].remove('%');
                        inVoltage=QString("%1").arg(rangev.toDouble() * percentv.toDouble() / 100.0);
                        xlsx.write(row,++colTmp,inVoltage,format2);
                        xlsx.write(row+1,colTmp,inVoltage,format2);

                        rangec=parmAry[0].replace("A","").replace("mA","");
                        percentc=parmAry[1].remove('%');
                        inCurrent=QString("%1").arg(rangec.toDouble() * percentc.toDouble() / 100.0);
                        xlsx.write(row,++colTmp,inCurrent,format2);
                        xlsx.write(row+1,colTmp,inCurrent,format2);

                        xlsx.write(row,++colTmp,"1.0",format2);
                        xlsx.write(row+1,colTmp,"1.0",format2);

                        xlsx.write(row+rowOffsetAcmc,++colTmp,"标准表",format2);
                        xlsx.write(row+rowOffsetAcmc+1,colTmp,"EUT",format2);
                    }
                    col=7+colOffsetC;
                    innerValue=itemData->Attribute("ReferenceValue");
                    auto tempAry=innerValue.split(";");
                    for (auto istr:tempAry) {
                        xlsx.write(row+rowOffsetAcmc,++col,istr,format2);
                    }

                    innerValue=itemData->Attribute("ReferenceValue2");
                    tempAry=innerValue.split(";");
                    for (auto istr:tempAry) {
                        xlsx.write(row+rowOffsetAcmc,++col,istr,format2);
                    }

                    calcuCons(QString(itemData->Attribute("Conclusion")),formats);

                    col=7+colOffsetC;
                    innerValue=itemData->Attribute("MeasuredValue");
                    tempAry=innerValue.split(";");
                    int i=0;
                    for (auto istr:tempAry) {
                        xlsx.write(row+rowOffsetAcmc+1,++col,istr,formats[i]);
                        ++i;
                    }

                    innerValue=itemData->Attribute("MeasuredValue2");
                    tempAry=innerValue.split(";");
                    i=3;
                    for (auto istr:tempAry) {
                        xlsx.write(row+rowOffsetAcmc+1,++col,istr,formats[i]);
                        ++i;
                    }

                    innerValue=itemData->Attribute("ErrorValue");
                    tempAry=innerValue.split(";");
                    i=0;
                    for (auto istr:tempAry) {
                        xlsx.write(row+rowOffsetAcmc+1,++col,istr,formats[i]);
                        ++i;
                    }

                    innerValue=itemData->Attribute("ErrorValue2");
                    tempAry=innerValue.split(";");
                    i=3;
                    for (auto istr:tempAry) {
                        xlsx.write(row+rowOffsetAcmc+1,++col,istr,formats[i]);
                        ++i;
                    }

                    itemData=itemData->NextSiblingElement();
                    row+=2;
                }
                rowOffsetAcmc=row;
            }
            else if (0==strcmp("ACMeterError",firstGroupOfItems->Attribute("GroupName"))) {
                offsetType=3;

                if(!xlsx.selectSheet(sheetErrorName))
                {
                    xlsx.addSheet(sheetErrorName);
                }
                tinyxml2::XMLElement *firstItemsOfGroup = firstGroupOfItems->FirstChildElement("Items");
                tinyxml2::XMLElement *itemData=firstItemsOfGroup->FirstChildElement();
                QString innerValue;
                int col=0+colOffset_sheet2;
                int row=3;
                while(itemData){
                    if(count==0){
                        int colTmp=0;
                        xlsx.write(row,++colTmp,QString(itemData->Attribute("Index")).toInt()+1,format2);
                        auto parmAry=QString(itemData->Attribute("Parameter")).split("_");
                        xlsx.write(row,++colTmp,parmAry[0],format2);
                        xlsx.write(row,++colTmp,parmAry[1],format2);

                        rangev=parmAry[2].replace("V","").replace("mV","");
                        percentv=parmAry[3].remove('%');
                        inVoltage=QString("%1").arg(rangev.toDouble() * percentv.toDouble() / 100.0);
                        xlsx.write(row,++colTmp,inVoltage,format2);

                        rangec=parmAry[4].replace("A","").replace("mA","");
                        percentc=parmAry[5].remove('%');
                        inCurrent=QString("%1").arg(rangec.toDouble() * percentc.toDouble() / 100.0);
                        xlsx.write(row,++colTmp,inCurrent,format2);

                        xlsx.write(row,++colTmp,parmAry[6],format2);
                        xlsx.write(row,++colTmp,parmAry[7].split('&')[1],format2);
                        xlsx.write(row,++colTmp,parmAry[7].split('&')[0],format2);
                    }

                    innerValue=itemData->Attribute("ErrorValue");
                    if("2"==QString(itemData->Attribute("Conclusion")).trimmed()){
                        formatError.setFontColor(QColor(Qt::red));
                    }else if("4"==QString(itemData->Attribute("Conclusion")).trimmed()){
                        formatError.setFontColor(QColor(Qt::blue));
                    }else{
                        formatError.setFontColor(QColor(Qt::black));
                    }

                    xlsx.write(row,9+colOffset_sheet2,innerValue,formatError);

                    col=9+colOffset_sheet2;
                    innerValue=itemData->Attribute("ErrorValue2");
                    auto tempAry=innerValue.split(";");
                    for (auto istr:tempAry) {
                        xlsx.write(row,++col,istr,formatError);
                    }
                    if(tempAry.size() > maxOffsetError)
                        maxOffsetError=tempAry.size();

                    itemData=itemData->NextSiblingElement();
                    ++row;
                }

            }

            if(offsetType==1){
                int rowTmp=2;
                int colTmp=0;
                if(!count){
                    xlsx.write(rowTmp,++colTmp,"序号",format1);
                    xlsx.write(rowTmp,++colTmp,"接线方式",format1);
                    xlsx.write(rowTmp,++colTmp,"元件",format1);
                    xlsx.write(rowTmp,++colTmp,"电压(V)",format1);
                    xlsx.write(rowTmp,++colTmp,"电流(A)",format1);
                    xlsx.write(rowTmp,++colTmp,"功率因数",format1);
                    xlsx.write(rowTmp,++colTmp,"设备",format1);
                }else {
                    colTmp=7;
                }
                xlsx.write(1,++colTmp+colOffset,deviceNo + " " + testDate,format1);
                xlsx.mergeCells(CellRange(1,colTmp+colOffset,1,colTmp+colOffset+12-1),format1);

                colTmp+=colOffset-1;
                xlsx.write(rowTmp,++colTmp,"幅值A",format1);
                xlsx.write(rowTmp,++colTmp,"幅值B",format1);
                xlsx.write(rowTmp,++colTmp,"幅值C",format1);
                xlsx.write(rowTmp,++colTmp,"相位A(°)",format1);
                xlsx.write(rowTmp,++colTmp,"相位B(°)",format1);
                xlsx.write(rowTmp,++colTmp,"相位C(°)",format1);
                xlsx.write(rowTmp,++colTmp,"误差A(%)",format1);
                xlsx.write(rowTmp,++colTmp,"误差B(%)",format1);
                xlsx.write(rowTmp,++colTmp,"误差C(%)",format1);
                xlsx.write(rowTmp,++colTmp,"误差A(°)",format1);
                xlsx.write(rowTmp,++colTmp,"误差B(°)",format1);
                xlsx.write(rowTmp,++colTmp,"误差C(°)",format1);
            }
            else if (offsetType==2) {
                int rowTmp=2;
                int colTmp=0;
                if(!count){
                    xlsx.write(rowTmp,++colTmp,"组号",format1);
                    xlsx.write(rowTmp,++colTmp,"接线方式",format1);
                    xlsx.write(rowTmp,++colTmp,"元件",format1);
                    xlsx.write(rowTmp,++colTmp,"电压(V)",format1);
                    xlsx.write(rowTmp,++colTmp,"电流(A)",format1);
                    xlsx.write(rowTmp,++colTmp,"功率因数",format1);
                    xlsx.write(rowTmp,++colTmp,"设备",format1);
                }else {
                    colTmp=7;
                }
                xlsx.write(1,++colTmp+colOffsetC,deviceNo + " " + testDate,format1);
                xlsx.mergeCells(CellRange(1,colTmp+colOffsetC,1,colTmp+colOffsetC+12-1),format1);

                colTmp+=colOffsetC-1;
                xlsx.write(rowTmp,++colTmp,"幅值A",format1);
                xlsx.write(rowTmp,++colTmp,"幅值B",format1);
                xlsx.write(rowTmp,++colTmp,"幅值C",format1);
                xlsx.write(rowTmp,++colTmp,"相位A(°)",format1);
                xlsx.write(rowTmp,++colTmp,"相位B(°)",format1);
                xlsx.write(rowTmp,++colTmp,"相位C(°)",format1);
                xlsx.write(rowTmp,++colTmp,"误差A(%)",format1);
                xlsx.write(rowTmp,++colTmp,"误差B(%)",format1);
                xlsx.write(rowTmp,++colTmp,"误差C(%)",format1);
                xlsx.write(rowTmp,++colTmp,"误差A(°)",format1);
                xlsx.write(rowTmp,++colTmp,"误差B(°)",format1);
                xlsx.write(rowTmp,++colTmp,"误差C(°)",format1);
            }
            else if (offsetType==3) {
                int rowTmp=2;
                int colTmp=0;
                if(!count){
                    xlsx.write(rowTmp,++colTmp,"序号",format1);
                    xlsx.write(rowTmp,++colTmp,"接线方式",format1);
                    xlsx.write(rowTmp,++colTmp,"元件",format1);
                    xlsx.write(rowTmp,++colTmp,"电压(V)",format1);
                    xlsx.write(rowTmp,++colTmp,"电流(A)",format1);
                    xlsx.write(rowTmp,++colTmp,"功率因数",format1);
                    xlsx.write(rowTmp,++colTmp,"方向",format1);
                    xlsx.write(rowTmp,++colTmp,"功率类型",format1);
                }else {
                    colTmp=8;
                }
                xlsx.write(1,++colTmp+colOffset_sheet2,deviceNo + " " + testDate,format1);
                xlsx.mergeCells(CellRange(1,colTmp+colOffset_sheet2,1,colTmp+colOffset_sheet2+maxOffsetError),format1);

                colTmp+=colOffset_sheet2-1;
                xlsx.write(rowTmp,++colTmp,"平均误差(%)",format1);
                for (int i=1;i<=maxOffsetError;++i) {
                    xlsx.write(rowTmp,++colTmp,QString("误差%1(%)").arg(i),format1);
                }
            }

            firstGroupOfItems=firstGroupOfItems->NextSiblingElement();
        }//while

        colOffset+=12;
        colOffsetC+=12;
        colOffset_sheet2+=maxOffsetError+1;

        ++count;
    }//for

    QDir dir;
    if (!dir.exists(dir_str))
        dir.mkpath(dir_str);
    if(count)
        xlsx.saveAs(dir_str + "/Refm(" + QString::number(count) + ")" + QDateTime::currentDateTime().toString("yyyy-MM-dd hhmmss") + ".xlsx");
    xlsx.destroyed();
    return 1;
}
void calcuCons(const QString &constrs,Format (&formats)[6]){
    for (decltype (constrs.size()) i=0;i<6;++i) {
        if(i*2<constrs.size()){
            if('2'==constrs[i*2]){
                formats[i].setFontColor(QColor(Qt::red));
            }else if('4'==constrs[i*2]){
                formats[i].setFontColor(QColor(Qt::blue));
            }else {
                formats[i].setFontColor(QColor(Qt::black));
            }
        }else {
            formats[i].setFontColor(QColor(Qt::black));
        }
    }
}
